package com.sky.service.impl;

import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.DigitUtils;
import com.sky.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    // 根据用户名查找用户
    public User findByUsername(String username) {
        // 调用UserMapper中的findByUsername方法，根据用户名查找用户
        User user = userMapper.findByUsername(username);
        // 返回查找到的用户
        return user;
    }

    @Override
    public void register(String username, String password) {
        String pass = DigitUtils.md5DigestAsHex(password);
        // 调用UserMapper中的insert方法，插入用户
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();
        userMapper.insert(username, pass, createTime, updateTime);

    }

    @Override
    public void update(User user) {
        // 调用UserMapper中的update方法，更新用户信息
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    // 更新密码
    @Override
    public void updatePassword(String newPassword) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePassword(DigitUtils.md5DigestAsHex(newPassword), id);
    }
}
